package com.springboot.last_experiment.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.springboot.last_experiment.commmon.WechatUtil;
import com.springboot.last_experiment.dao.UserDao;
import com.springboot.last_experiment.entity.User;
import com.springboot.last_experiment.vo.ResultVO;
import com.springboot.last_experiment.voutils.ResultVOUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Transactional
@Service
public class UserService {
    @Autowired
    private UserDao userDao;


    /**
     *
     * @param code 接收小程序发送的code
     * @param rawData 用户非敏感信息
     * @param signature 签名
     * @return
     */
    public ResultVO user_login(String code, String rawData, String signature) {
        JSONObject rawDataJson = JSON.parseObject(rawData);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            return ResultVOUtil.error(500, "签名校验失败");
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
        User user = userDao.selectById(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        if (user == null) {
            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String gender = rawDataJson.getString("gender");
            String picture = rawDataJson.getString("avatarUrl");
            user = new User();
            user.setSex(Integer.parseInt(gender));
            user.setOpenid(openid);
            user.setNick(nickName);
            user.setPicture(picture);
            user.setSkey(skey);
            user.setStatus(0);
            user.setIsLock(0);
            user.setRole(0);
            try{
                userDao.insert(user);
            }catch (Exception e){
                return ResultVOUtil.error(500,"用户添加异常");
            }
        } else {
            //判断账号是否被锁定
            if(user.getIsLock()==1){
                return ResultVOUtil.error(500,"该账号被锁定，无法登录");
            }
            // 重新设置会话skey
            user.setSkey(skey);
            try{
                userDao.update(user);
            }catch (Exception e){
                return ResultVOUtil.error(500,"重新设置会话skey");
            }
        }

        //6. 把新的skey返回给小程序
        return ResultVOUtil.success(user);
    }

    public ResultVO user_register(User user){
        String openid = user.getOpenid();
        User user1 = userDao.selectById(openid);
        user1.setUserId(user.getUserId());
        user1.setName(user.getName());
        user1.setAddress(user.getAddress());
        user1.setPhone(user.getPhone());
        user1.setIsResident(user.getIsResident());
        user1.setIsVerify(0);
        try {
            userDao.update(user1);
        }catch (Exception e){
            return ResultVOUtil.error(500,"修改异常");
        }
        return  ResultVOUtil.success(null);
    }

    public ResultVO user_update(User user){
        String openid = user.getOpenid();
        User user1 = userDao.selectById(openid);
        user1.setUserId(user.getUserId());
        user1.setName(user.getName());
        user1.setAddress(user.getAddress());
        user1.setPhone(user.getPhone());
        user1.setIsResident(user.getIsResident());
        user1.setSex(user.getSex());
        if(!(user1.getSkey().equals(user.getSkey()))){
            return ResultVOUtil.error(500,"skey验证错误");
        }
        try {
            userDao.update(user1);
        }catch (Exception e){
            return ResultVOUtil.error(500,"修改异常");
        }
        return  ResultVOUtil.success(null);
    }

    public ResultVO user_selectById(String openid,String skey){
        User user1 = userDao.selectBySkey(skey);
        if(user1==null){
            return ResultVOUtil.error(500,"skey校验失败");
        }
        User user=null;
        try{
            user = userDao.selectById(openid);
        }catch (Exception e){
            return ResultVOUtil.error(500,"查询异常");
        }
        return ResultVOUtil.success(user);
    }
    public ResultVO user_selectById(String openid){
        User user = userDao.selectById(openid);
        System.out.println(user);
        return ResultVOUtil.success(user);
    }
    public ResultVO lockUser(String openid){
        User user = userDao.selectById(openid);
        if(user.getIsLock()==1){
            try{
                userDao.unlockUser(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"解锁定账号异常");
            }
        }else{
            try{
                userDao.lockUser(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"锁定账号异常");
            }
        }

        return ResultVOUtil.success(null);
    }

    public ResultVO updateRole(String openid){
        User user = userDao.selectById(openid);
        if(user.getRole()==1){
            try{
                userDao.updateRes(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"修改为住户异常");
            }
        }else{
            try{
                userDao.updateIns(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"修改为检查人员异常");
            }
        }

        return ResultVOUtil.success(null);
    }

    public ResultVO selectAllUser(){
        List<User> users = userDao.selectAll();
        return ResultVOUtil.success(users) ;
    }

    public ResultVO getUserByKey(String key){

        List<User> resByKey = userDao.getUserByKey(key);
        return ResultVOUtil.success(resByKey);
    }

    public ResultVO updateStatus(String openid,Integer status)
    {
        try{
            userDao.updateStatus(openid,status);
        }catch (Exception e){
            return ResultVOUtil.error(500,"修改状态异常");
        }
        return ResultVOUtil.success(null);
    }

    public ResultVO updateCheck(String openid,Integer check)
    {

        if(check==1){
            try{
                userDao.updateCheck(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"修改审核情况异常");
            }
        }else{
            try {
                userDao.deleteUser(openid);
            }catch (Exception e){
                return ResultVOUtil.error(500,"删除注册信息异常");
            }
        }

        return ResultVOUtil.success(null);
    }
}
